

# 2048 核心算法
debug = True
if debug:
    map_data = [
        [2,  8, 8, 2],
        [4, 16, 0, 2],
        [8,  2, 0, 0],
        [2,  8, 0, 0],
    ]
else:
    map_data = [
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
    ]

def left_move_number(aline_list):
    '''将所有的数字靠左对齐，0放在右侧'''
    for _ in range(3):
        for i in range(3):
            if aline_list[i] == 0:
                aline_list[i] = aline_list[i+1]
                aline_list[i+1] = 0

def left_merge_number(aline_list):
    '''自左向右合并相邻的数据（两个值项等就合并）
    [2, 8, 8, 2] ----> [2, 16, 0, 2]
    [8, 8, 2, 2] ----> [16, 0, 4, 0]
    '''
    for i in range(3):
        if aline_list[i] == aline_list[i+1]:
            aline_list[i] *= 2
            aline_list[i+1] = 0

# 核心算法1
def left_move_aline(aline_list):
    # 分三步走
    # 1. 第一步，全部左移不合并
    left_move_number(aline_list)
    # 2. 第二步，自左向右合并相邻的数据（两个值项等就合并）
    left_merge_number(aline_list)
    # 3. 第三步，全部左移不合并
    left_move_number(aline_list)

# 基本操作，
def left():
    '左移'
    for aline in map_data:
        left_move_aline(aline)

def right():
    '右移'
def up():
    '上移'
def down():
    '下移'

def show_map():
    for aline in map_data:
        print('+------+------+------+------+')
        s = '| ' + ' | '.join([str(x).center(4) for x in aline]) + ' |'
        print(s)
    print('+------+------+------+------+')


def main():
    while True:
        show_map()
        s = input('请按键：a/s/d/w:')
        if s == 'a':
            left()
        elif s == 'd':
            right()
        elif s == 's':
            down()
        elif s == 'w':
            up()

#     map_data = [
#         [2,  8, 8, 2],
#         [4, 16, 0, 2],
#         [8,  2, 0, 0],
#         [2,  8, 0, 0],
#     ]

if __name__ == '__main__':
    main()
    # line1 = [0, 0, 0, 2]
    # print(line1)
    # left_move_number(line1)
    # print(line1)  # [8, 0, 2， 0]
    # line2 = [8, 8, 2, 2]
    # print(line2)
    # left_move_aline(line2)
    # print(line2)
